<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>群组管理</el-breadcrumb-item>
      <el-breadcrumb-item>群组列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图区域-->
    <el-card class="box-card">
      <!--搜索与添加区域-->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入群组名称" v-model="queryInfo.query" clearable @clear="getGroupList()">
            <el-button slot="append" icon="el-icon-search" @click="getGroupList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="Jump">创建群组</el-button>
        </el-col>
      </el-row>

      <!--用户列表区域-->
      <el-table :data="this.showGroupList" highlight-current-row
                :row-class-name="tableRowClassName" @row-click = "onRowClick" border stripe>
        <el-table-column label="#" type="index">

        </el-table-column>
        <el-table-column label="群组id" prop="id">
        </el-table-column>
        <el-table-column label="群组名称" prop="name">
        </el-table-column>
        <el-table-column label="所属用户id" prop="userId" >
        </el-table-column>
<!--        <el-table-column label="所属用户" prop="username">-->
<!--        </el-table-column>-->
        <el-table-column label="可否修改/删除" prop="status" v-if="false">
        </el-table-column>
        <el-table-column label="群组描述" prop="description">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!--修改按钮-->
            <el-button type="success" icon="el-icon-view" size="mini" @click="showviewDialog(scope.row.id)"></el-button>
            <!--修改按钮-->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)"></el-button>
            <!--删除按钮-->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeGroupById(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--查看答者的对话框-->
    <el-dialog
      title="查看答者名单"
      :visible.sync="viewDialogVisible"
      width="70%"
      @close="viewDialogClosed">
      <!--内容主体区域-->
<!--        <el-table :data="showAnswerList" highlight-current-row ref="viewFormRef"-->
<!--                  :row-class-name="tableRowClassName" @row-click = "onRowClick" border stripe>-->
<!--      删除 表格不同行的样式-->
      <el-table :data="showAnswerList" highlight-current-row ref="viewFormRef"
                 @row-click = "onRowClick" border stripe>
          <el-table-column label="#" type="index">
          </el-table-column>
<!--          <el-table-column label="群组id" prop="groupId">-->
<!--          </el-table-column>-->
          <el-table-column label="答者id" prop="id">
          </el-table-column>
          <el-table-column label="答者账号" prop="username">
          </el-table-column>
          <el-table-column label="答者名称" prop="name">
          </el-table-column>
          <el-table-column label="手机号码" prop="phone">
          </el-table-column>
          <el-table-column label="邮箱" prop="email">
          </el-table-column>
        </el-table>
      <el-pagination
        @size-change="AnhandleSizeChange"
        @current-change="AnhandleCurrentChange"
        :current-page="queryInfoForReplier.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfoForReplier.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="answertotal">
      </el-pagination>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="viewDialogVisible = false">确 定</el-button>
            </span>
    </el-dialog>

    <!--修改群组的对话框-->
    <el-dialog
      title="修改群组"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClosed">
      <!--修改用户内容区域-->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="群组名称" prop="groupname">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="discription">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editGroup">确 定</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 验证手机号的规则
    var checkMobile = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        // 合法的邮箱
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }

    return {
      currentRowIndex: 1,
      // 已选中的校色id值
      selectedRoleId: '',
      // 是否显示分配角色对话框
      setRoleDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {
        id: '',
        name: '',
        description: ''
      },
      editFormRules: {
        email: [
          { require: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 10, message: '用户账号的长度在3~10个字符之间', trigger: 'blur' }
        ],
        phone: [
          { require: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制修改用户对话框的显示和隐藏
      viewDialogVisible: false,
      // 控制修改用户对话框的显示和隐藏
      editDialogVisible: false,
      // 控制添加用户对话框的显示和隐藏
      addDialogVisible: false,

      // 获取答者列表的参数对象

      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        pagesize: 5
      },
      queryInfoForReplier: {
        pagenum: 1,
        pagesize: 5
      },
      // 答者列表信息
      answerlist: [{
        angroupid: '20204566',
        answerid: '1234',
        answername: '张洞洞租',
        phone: '13188723672',
        email: '55588832@qq.com'
      }],
      answertotal: 1,
      showAnswerList: [],

      // 保存一个群组列表信息
      grouplist: [{
        groupid: '20204566',
        groupname: '张洞洞租',
        username: '26548575',
        discription: '18601342954'
      }, {
        groupid: '895641',
        groupname: '林瑶瑶',
        username: '5815264',
        discription: '18601342954',

      }, {
        groupid: '526334',
        groupname: '流星',
        username: '5858',
        discription: '1860134564',

      }, {
        groupid: '8978',
        groupname: '林56',
        username: '5815264',
        discription: '18602524',

      }, {
        groupid: '865',
        groupname: '895',
        username: '581544',
        discription: '152524',

      }, {
        groupid: '525',
        groupname: '895',
        username: '21544',
        auth: 3,
        discription: '152524',
      }],
      total: 4,
      showGroupList: [],
    }
  },
  created () {
    // this.getAnswerList(),
    this.getGroupList()
  },
  methods: {
    tableRowClassName ({ row, rowIndex }) {
      row.row_index = rowIndex
    },
    onRowClick (row, event, column) {
      this.currentRowIndex = row.row_index
    },
    // 跳转页面
    Jump () {
      this.$router.push('/creategroup')
    },
    // 根据id进行群组信息的删除
    async removeGroupById (row) {
      // 弹框进行提示，询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该群组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })

      // 如果用户确认删除，则返回confirm
      // 如果用户取消删除，则返回cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      if (row.status === 0) {
        return this.$message.info('该群组有数据关联 不可删除')
      }
      await this.$http.delete('/groups/delete/' + row.id)
      this.$message.error('删除群组成功')
      this.getGroupList()
      // console.log(confirmResult)
    },
    // 修改用户信息并提交
    editGroup () {
      this.$http.put('groups/edit', this.editForm).then((res) => {
        this.$message.success('更新群组信息成功')
        this.editDialogVisible = false
        this.getGroupList()
      })
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed () {
      // 对表单字段内容重置
      this.$refs.editFormRef.resetFields()
    },
    // 展示答者名单的对话框
     async showviewDialog (id) {
      // 给答者表赋值
      await this.getAnswerList(id)
      this.viewDialogVisible = true
    },
    // 展示编辑用户的对话框
    async showEditDialog (row) {
      this.editForm = {
        id: row.id,
        name: row.name,
        description: row.description
      }
      // 显示对话框
      this.editDialogVisible = true
    },

    viewDialogClosed () {
      // this.$refs.viewFormRef.resetFields()
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听swith用户状态开关的改变
    userStateChanged (groupinfo) {
      // 打印状态信息
      console.log(groupinfo.mg_state)

      // 这里应该发送http请求
      var len = this.grouplist.length
      for (var i = 0; i < len; i++) {
        var group = this.grouplist[i]
        if (group.groupid == groupinfo.groupid) {
          group.mg_state = groupinfo.mg_state
        }
      }
      getGroupList()
    },
    // 监听pageSize改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getGroupList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getGroupList()
    },
    AnhandleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getAnswerList()
    },
    // 监听页码值改变的事件
    AnhandleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getAnswerList()
    },
      // 获取答者列表并分页
     getAnswerList (id) {
       this.$http.get('user/list', {
         params: {
           auth: 4,
           used: 1,
           superId: this.Global.globalUser.globalID,
           groupId: id
         }
       }).then((response) => {
         this.showAnswerList = []
         let len = response.data.data.length
         const searchAnswerList = []
         for (let i = 0; i < len; i++) {
           const answer = response.data.data[i]
           // if (this.queryInfo.query !== '') {
           //   if (answer.name.indexOf(this.queryInfo.query) !== -1) {
           //     searchAnswerList.push(answer)
           //   }
           // } else {
             searchAnswerList.push(answer)
           // }
         }
         // 获取对应的记录列表
         const start = (this.queryInfoForReplier.pagenum - 1) * this.queryInfoForReplier.pagesize
         len = searchAnswerList.length
         for (let i = 0; i < len; i++) {
           if (i >= start && i < start + this.queryInfoForReplier.pagesize) {
             const answer = searchAnswerList[i]
             this.showAnswerList.push(answer)
           }
         }
         this.answertotal = searchAnswerList.length
         console.log(555)
         console.log(this.showAnswerList)
       })
    },
    getGroupList () {
      this.$http.get('groups/list', {
        params: {
          used: 1,
          userId: this.Global.globalUser.globalID
        }
      }).then((response) => {
        this.showGroupList = []
        let len = response.data.data.length
        const searchGroupList = []
        for (let i = 0; i < len; i++) {
          const group = response.data.data[i]
          // group.createTime = new Date(group.createTime).toLocaleString()
          if (this.queryInfo.query !== '') {
            if (group.name.indexOf(this.queryInfo.query) !== -1) {
              searchGroupList.push(group)
            }
          } else {
            searchGroupList.push(group)
          }
        }
        console.log(searchGroupList)
        const start = (this.queryInfo.pagenum - 1) * this.queryInfo.pagesize
        len = searchGroupList.length
        for (let i = 0; i < len; i++) {
          if (i >= start && i < start + this.queryInfo.pagesize) {
            const group = searchGroupList[i]
            this.showGroupList.push(group)
          }
        }
        this.total = searchGroupList.length
        this.grouplist = this.showGroupList
      })
    }
  }
}
</script>

<style lang="less" scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}

.box-card {
  width: 100%;
}
</style>
